#!/bin/bash

BASH_DIR=$(cd "$(dirname "$0")" && pwd)
TODAY=$(date +%Y%m%d)
LOG_DIR=$BASH_DIR/$TODAY
if [ -d "$LOG_DIR" ]
then
  echo $LOG_DIR
else
  cd $BASH_DIR
  mkdir -p "$LOG_DIR"
  echo "创建日志目录: $LOG_DIR"
fi
LOG_FILE="$LOG_DIR/ftp_upload.log"
: > "$LOG_FILE"  # 清空日志文件

# 配置参数
REMOTE_HOST="127.0.0.1"
REMOTE_PORT="21"
USERNAME="appoper"
PASSWORD="q1w2E#R$"

# 固定目录结构
LOCAL_BASE_DIR=E:/workSpace/RuoYi-Vue-3.8.8/ruoyi-ftp/home/ap/appoper
REMOTE_BASE_DIR=/home/ap/appoper_1
DATA_DIR=MANAGE_DATA

# 动态生成上个月的目录名
MONTH_DIR=$(date -d "1 month ago" +%Y%m)

# 记录日志函数
log() {
    local level="$1"
    shift
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"
}
# 构建完整路径
LOCAL_PATH="${LOCAL_BASE_DIR}/${MONTH_DIR}/${DATA_DIR}"
REMOTE_PATH="${REMOTE_BASE_DIR}/${MONTH_DIR}/${DATA_DIR}"
log "INFO" "=== 启动文件上传任务 ==="
# 本地路径检查
if [ ! -d "$LOCAL_PATH" ]; then
  log "ERROR" "错误：本地目录不存在 $LOCAL_PATH"
  exit 1
elif [ -z "$(ls -A "$LOCAL_PATH")" ]; then
  log "ERROR" "错误：本地目录为空 $LOCAL_PATH"
  exit 1
fi

log "INFO" "=== 本地目录校验通过 ==="
log "INFO" ${LOCAL_PATH}

# 创建FTP脚本
FTP_SCRIPT=$(mktemp)
{
  echo "user $USERNAME $PASSWORD"
  echo "cd $REMOTE_BASE_DIR"
  # 创建动态月份目录
  echo "mkdir $MONTH_DIR"
  echo "cd $MONTH_DIR"
  # 创建数据目录
  echo "mkdir $DATA_DIR"
  echo "cd $DATA_DIR"
  # 文件传输设置
  echo "lcd $LOCAL_PATH"
  echo "binary"
  echo "prompt"
  echo "mput *"
  echo "bye"
} > "$FTP_SCRIPT"

# 执行FTP传输
log "INFO" "=== FTP文件传输详情 ===" 
log "INFO" "本地路径: ${LOCAL_PATH}" 
log "INFO" "远程路径: ${REMOTE_PATH}" 
log "INFO" "FTP脚本执行具体内容:" 
cat "${FTP_SCRIPT}"

# 简化FTP命令，移除可能引起问题的-p参数
ftp -n -v <<EOF >> "${LOG_FILE}" 2>&1
open ${REMOTE_HOST} ${REMOTE_PORT}
$(cat "${FTP_SCRIPT}")
EOF

# 错误处理 - 基于日志内容检测真实状态
if grep -q "226 Transfer complete." "${LOG_FILE}" 
then
  log "INFO" "=== FTP文件传输成功 ==="
  rm -f "${FTP_SCRIPT}"
  log "INFO" "文件成功上传至: ${REMOTE_PATH}"
  exit 0
else
  log "ERROR" "=== FTP文件传输失败 ==="
  log "ERROR" "可能原因:详见日志文件 $LOG_FILE"
  grep -q "530 " "${LOG_FILE}" && log "ERROR" "- 用户名/密码错误"
  grep -q "Connection refused" "${LOG_FILE}" && log "ERROR" "- 服务器连接失败"
  grep -q "550 " "${LOG_FILE}" && log "ERROR" "- 目录权限不足"
  # 清理临时文件
  rm -f "${FTP_SCRIPT}"
  exit 1
fi
